package top.lixunda.common.validate.validate;

import top.lixunda.common.validate.annotation.XumEndWith;
import top.lixunda.common.validate.core.ValidateError;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;

/**
 * @author Xumda
 * @version time:2019/12/9 13:15
 *
 * 对toString 进行验证
 */
public class EndWithValidate implements AnnotationValidate {

    @Override
    public boolean support(Class annotationClass) {
        return XumEndWith.class.equals(annotationClass);
    }

    @Override
    public ValidateError valid(Annotation annotation, Field field, Object obj, Object value, AnnotationCacheValidate handler) {
        XumEndWith a = (XumEndWith) annotation;
        boolean isNull = (value == null || (value instanceof String && "".equals(value)));
        if (isNull) {
            return null;
        }
        return value.toString().endsWith(a.value()) ?
                null : new ValidateError(getErrorMessage(a.message(), field, value, a.value()));
    }

    private String getErrorMessage(String message, Field field, Object value, String endWith) {
        return "".equals(message)
                ? field.getName() + "应以 " + endWith + " 结束"
                : message.replaceAll("#value#", String.valueOf(value)).replaceAll("#name#", field.getName());
    }

}
